package com.learn.security.modules.security.weixin;

import com.learn.security.modules.security.CustomUserDetailsService;
import com.learn.security.modules.security.handler.JCAuthenticationFailureHandler;
import com.learn.security.modules.security.handler.JCAuthenticationSuccessHandler;
import com.learn.security.modules.wx.mp.config.WxMpProperties;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

@Component
public class WeixinCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private CustomUserDetailsService userDetailsService;
    @Autowired
    private JCAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private JCAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WxMpProperties properties;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        WeixinCodeAuthenticationFilter weixinCodeAuthenticationFilter = new WeixinCodeAuthenticationFilter();
        weixinCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        weixinCodeAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        weixinCodeAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        WeixinCodeAuthenticationProvider weixinCodeAuthenticationProvider = new WeixinCodeAuthenticationProvider();
        weixinCodeAuthenticationProvider.setUserDetailsService(userDetailsService);
        weixinCodeAuthenticationProvider.setWxService(wxMpService);
        weixinCodeAuthenticationProvider.setProperties(properties);

        http.authenticationProvider(weixinCodeAuthenticationProvider)
                .addFilterAfter(weixinCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
